﻿using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using ImageGallery.DAL;
using System;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ImagesService
{
    [OperationContract]
    public ResultData GetImages(int startRowIndex, int maximumRows)
    {
        ResultData result = new ResultData();
        IQueryable<Photo> ds = PhotoDAO.GetAll();
        var query = (from img in ds
                     select new Image
                     {
                         PhotoID = img.PhotoID,
                         Title = img.Title,
                         Location = img.Location,
                         Description = img.Description,
                         Rating = img.Rating,
                         Data = img.Data,
                         RatesCount = img.RatesCount
                     });

        result.Count = query.Count();
        result.Data = query.Skip(startRowIndex).Take(maximumRows).ToList();

        return result;
    }

    [DataContract]
    public class Image
    {
        double? rating;

        [DataMember]
        public int PhotoID { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public string Location { get; set; }
        [DataMember]
        public string Description { get; set; }
        [DataMember]
        public double? Rating
        {
            get
            {
                if (rating.HasValue)
                {
                    return Math.Round(rating.Value, 2);
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                rating = value;
            }
        }
        [DataMember]
        public byte[] Data { get; set; }
        [DataMember]
        public int? RatesCount { get; set; }
    }

    public class ResultData
    {
        public int Count { get; set; }
        public List<Image> Data { get; set; }
    }
}